package cn.rengy.tpa.wxmp.token;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tool.http.HttpUtils;
import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.util.WeChatReturnCode;

public class AccessTokenApi {
	private static Logger logger = LoggerFactory.getLogger(AccessTokenApi.class);
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
	
	public static AccessTokenResponse token(String appid,String appsecret) throws WeChatException{
		StringBuilder sb=new StringBuilder(ACCESS_TOKEN_URL);
		sb.append("&appid=").append(appid).append("&secret=").append(appsecret);
		String url=sb.toString();
		int errcode=0;
		JSONObject jsonObject=null;
		for(int i=0;i<3;i++){
			String httpResult = HttpUtils.get(url);
			logger.debug("tokenResult:{}",httpResult);
			//System.out.println(httpResult);
			jsonObject = JSONObject.parseObject(httpResult);
			errcode=jsonObject.getIntValue("errcode");
			/**
			 *  -1	    系统繁忙，此时请开发者稍候再试
				0	    请求成功
				40001 AppSecret错误或者AppSecret不属于这个公众号，请开发者确认AppSecret的正确性
				40002 请确保grant_type字段值为client_credential
				40164 调用接口的IP地址不在白名单中，请在接口IP白名单中进行设置
			 */
			if(errcode==-1){
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {}
			}else{
				break;
			}
		}
		if(errcode==0){
			String access_token=jsonObject.getString("access_token");
			int expires_in=jsonObject.getIntValue("expires_in");
			return new AccessTokenResponse(access_token,  expires_in);
		}else{
			String errmsg=jsonObject.getString("errmsg");
			logger.error("获取token失败{}:{}",errcode,errmsg);
			throw new WeChatException(errcode,WeChatReturnCode.getMsg(errcode, errmsg));
		}
	}
}
